package com.zhuang.taiqiu.netty.handler;

import com.zhuang.taiqiu.proto.GameMessageOuterClass;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@ChannelHandler.Sharable
public class MyWebSocketChannelManageHandler extends ChannelInitializer<SocketChannel> {

    @Autowired
    private MyWebSocketHandler webSocketHandler;

    @Autowired
    private WebSocketProtobufHandler webSocketProtobufHandler;

    @Override
    protected void initChannel(SocketChannel e) throws Exception {
        e.pipeline()
                .addLast(new HttpResponseEncoder())
                .addLast(new HttpRequestDecoder())
                .addLast(new HttpObjectAggregator(65536))
                .addLast(new WebSocketServerProtocolHandler("/tq"))

                // Protobuf解码器与编码器
//                .addLast(new CustomProtobufDecoder(ChatMessage.getDefaultInstance()))
                .addLast(new ProtobufDecoder(GameMessageOuterClass.GameMessage.getDefaultInstance()))
                .addLast(new ProtobufEncoder())

                /**
                 *WebSocketServerProtocolHandler 对应websocket，它的数据是以 帧(frame)形式 传递
                 * 可以看到 WebSocketFrame 下有六个子类
                 * 浏览器请求时，ws://localhost:7000/XXX 表示请求的资源
                 * 核心功能是 将http协议升级为ws协议，保持长连接
                 */
                    .addLast("webSocketHandler",webSocketHandler) //第一个进入的处理器
                    .addLast("webSocketProtobufHandler",webSocketProtobufHandler);
//                    .addLast("protocolHandler",new WebSocketServerProtocolHandler("/websocket"))
////                    .addLast("nettyWebSocketHandler",nettyWebSocketHandler)
//                    .addLast("base_handler",myWebSocketHandler)
//                    .addLast("register_handler",registerHandler)
//                    .addLast("single_message",singleMessageHandler)
//                    .addLast("creat_group",creatGroupHandler)
//                    .addLast("group_message",groupMessageHandler)
////                    .addLast(HeartBeatRequestHandler.INSTANCE)
//                    .addLast(ExceptionHandler.INSTANCE);
    }
}